<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Models\Comment;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;

class ArticleController extends Controller
{
    public function record()
    {
        $commentCount = Comment::all()->count();

        $articleGroups = Article::select(DB::raw("DATE_FORMAT(created_at,'%Y-%m') as showtime"))->orderBy('showtime', 'desc')->groupBy(DB::raw("DATE_FORMAT(created_at,'%Y-%m')"))->get()->toArray();

        $articleRecords = Article::select('id', 'title', 'created_at')->withCount('comment')->orderBy('created_at', 'desc')->get()->toArray();

        $articleCount = count($articleRecords);

        foreach ($articleGroups as &$time) {
            foreach ($articleRecords as $record) {
                if (date('Y-m', strtotime($record['created_at'])) == $time['showtime']) {
                    $time['articles'][] = $record;
                }
            }
        }
        unset($time);

        return view('home.article.record', compact('articleGroups', 'commentCount', 'articleCount'));
    }

    public function detail($id)
    {
        $article = Article::query();
        $articleContent = $article->findorFail($id);
        $articleContent->increment('click', 1);
        $prev = $article->where('created_at', '>', $articleContent->created_at)->first();
        $next = $article->where('created_at', '<', $articleContent->created_at)->first();
        $comments = Comment::with('allChilds')->where(['comment_id' => 0, 'article_id' => $articleContent->id])->orderBy('created_at', 'desc')->get();
        return view('home.article.index', compact('articleContent', 'prev', 'next', 'comments'));
    }

    public function comment(Request $request, $id)
    {
        $member = auth()->guard('member')->user();
        $article = Article::findorFail($id);
        $data = [
            'article_id' => $article->id,
            'member_id' => $member->id,
            'comment_id' => $request->parent ?? 0,
            'content' => $request->text,
        ];
        DB::beginTransaction();
        try {
            DB::table('comments')->insert($data);
            DB::commit();
            return Redirect::back()->with('success', '评论成功');
        } catch (\Exception $exception) {
            DB::rollback();
            return Redirect::back()->with('error', '评论失败');
        }
    }
}
